package indv.Cning.cfengsecuritydemo.session;

import com.fasterxml.jackson.databind.ObjectMapper;
import indv.Cning.cfengsecuritydemo.domain.Resp;
import lombok.RequiredArgsConstructor;
import org.springframework.security.web.session.SessionInformationExpiredEvent;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;

import javax.servlet.ServletException;
import java.io.IOException;

/**
 * @author Cfeng
 * @date 2022/7/24
 */

@RequiredArgsConstructor
public class ParallelInformationExpiredStrategy implements SessionInformationExpiredStrategy {
    //处理对象转化的mapper，jackson工具将对象转为JSON格式,自动配置了对象
    private final ObjectMapper objectMapper;

    @Override
    public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException, ServletException {
        //返回异常信息
        event.getResponse().setContentType("application/json;charset=utf-8");
        event.getResponse().getWriter().write(objectMapper.writeValueAsString(Resp.failed("已达到并发上限")));
    }
}
